﻿using System;
using System.Xml;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Analysis;
using YArchitech.HCLoad.Utils;

namespace YArchitech.HCLoad.Export
{
	public class HcXmlCampus : HcXmlElement
	{
		public HcXmlCampus(HcDataManager dataManager) : base(dataManager)
		{
		}

		public override bool WriteElementData(ref XmlElement xmlelem_Campus)
		{
			base.WriteElementData(ref xmlelem_Campus);
			XmlDocument ownerDocument = xmlelem_Campus.OwnerDocument;
			XmlElement newChild = ownerDocument.CreateElement("Location");
			if (this.WriteElementData_Location(ref newChild, base.DataManager.Document.ActiveProjectLocation))
			{
				xmlelem_Campus.AppendChild(newChild);
			}
			XmlElement newChild2 = ownerDocument.CreateElement("Buidling");
			if (new HcXmlBuilding(base.DataManager).WriteElementData(ref newChild2))
			{
				xmlelem_Campus.AppendChild(newChild2);
			}
			this.CreateAndAppendElements_Suface(ref xmlelem_Campus);
			return true;
		}

		private bool WriteElementData_Location(ref XmlElement xmlelem_Location, ProjectLocation projectLocation)
		{
			EnergyDataSettings.GetFromDocument(base.DataManager.Document);
			double latitude = projectLocation.SiteLocation.Latitude;
			double longitude = projectLocation.SiteLocation.Longitude;
			City city = null;
			foreach (object obj in base.DataManager.Document.Application.Cities)
			{
				City city2 = (City)obj;
				if (HcUtils.DoubleEquals(city2.Latitude, latitude) && HcUtils.DoubleEquals(city2.Longitude, longitude))
				{
					city = city2;
					break;
				}
			}
			string name = projectLocation.Name;
			if (city != null)
			{
				name = city.Name;
			}
			HcXmlElement.AppendTextElement(ref xmlelem_Location, "Name", name);
			HcXmlElement.AppendTextElement(ref xmlelem_Location, "Latitude", HcUnit.AngleConverFromAPI(base.DataManager.Document, latitude).ToString());
			HcXmlElement.AppendTextElement(ref xmlelem_Location, "Longitude", HcUnit.AngleConverFromAPI(base.DataManager.Document, longitude).ToString());
			return true;
		}

		private bool CreateAndAppendElements_Suface(ref XmlElement xmlelem_Campus)
		{
			if (base.DataManager.SpaceDictionary.Count == 0)
			{
				return false;
			}
			XmlDocument ownerDocument = xmlelem_Campus.OwnerDocument;
			foreach (HcSurfaceData surfaceData in base.DataManager.HcSurfaces)
			{
				XmlElement newChild = ownerDocument.CreateElement("Surface");
				if (new HcXmlSurface(surfaceData).WriteElementData(ref newChild))
				{
					xmlelem_Campus.AppendChild(newChild);
				}
			}
			return true;
		}
	}
}
